import { readdirSync } from 'fs';
import fs from 'fs/promises';
import path from 'path';
import process from 'process';

import KoaRouter from '@koa/router';
import Koa from 'koa';

import { SERVER } from './loadConfig.ts';
import { getDirname } from './utils';

export class RouterPlus {
  static rootRouter = new KoaRouter({ prefix: SERVER.API_PREFIX });

  static async init(app: Koa) {
    app.use(this.rootRouter.routes()).use(this.rootRouter.allowedMethods());
    await this.loadControllers();
  }

  static async loadControllers() {
    if (process.env.NODE_ENV === 'production') {
      const controllerDir = path.join(process.cwd(), 'dist/controllers');
      const files = readdirSync(controllerDir);
      for (const file of files) {
        if (file.endsWith('.js')) {
          // 生产环境下是 .js 文件
          const modulePath = path.join(controllerDir, file);
          const fileUrl = `file:///${modulePath.replace(/\\/g, '/')}`;
          await import(fileUrl).catch((err) => {
            console.error(`Failed to load controller: ${file}`, err);
          });
        }
      }
    } else {
      const suffix = '.ts';
      const controllerDir = path.join(process.cwd(), '/src/controllers');
      const routerFiles = readdirSync(controllerDir);
      for (const file of routerFiles) {
        if (file.endsWith(`controller${suffix}`)) {
          const fullPath = path.join(controllerDir, file);
          const fileUrl = `file:///${fullPath.replace(/\\/g, '/')}`;
          await import(fileUrl).catch((err) => {
            console.log(err);
          });
        }
      }
    }
  }
}
